﻿/*
 * Copyright 2013 Shaun McCloud
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/ 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace Astrid_Desktop
{
    public static class Serialization
    {
        /// <summary>
        /// Serialize this class to an xml file
        /// </summary>
        /// <param name="inSettings">Settings to serialize</param>
        /// <param name="fileName">Filename to save to</param>
        /// <remarks></remarks>
        public static void SerializeSettingsAsXml<Settings>(Settings inSettings, string fileName)
        {
            string fName = SettingsFile(fileName);

            try
            {
                XmlSerializer x = new XmlSerializer(inSettings.GetType());
                using (StreamWriter writer = new StreamWriter(fName))
				{
                    x.Serialize(writer, inSettings);
				}
			}
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Deserialize a file into an instance of this class
        /// </summary>
        /// <param name="fileName">Filename to deserialize</param>
        /// <returns>Settings contained in format defined in Settings.cs</returns>
        /// <remarks></remarks>
        public static Settings DeserializeSettingsFromXml<Settings>(string fileName)
        {
            string fName = SettingsFile(fileName);

            try
            {
                XmlSerializer x = new XmlSerializer(typeof(Settings));
                using (StreamReader reader = new StreamReader(fName))
				{
                    return (Settings)x.Deserialize(reader);
				}
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static string SettingsFile(string fileName)
        {
            if (!fileName.Contains("\\"))
            {
                return Directory.GetCurrentDirectory() + "\\" + fileName;
            }
            else
            {
                return fileName;
            }
        }
    }
}
